<?php

namespace App\Repositories\Acl;

use Prettus\Repository\Eloquent\BaseRepository as Repository;
use App\Events\UpdateStaffPermissionEvent;

class StaffRepository extends Repository
{
    protected $guard = 'admin';

    function model()
    {
        return 'App\Models\Acl\Staff';
    }


    public function index($query = '')
    {
        $supervisor = \Config::get('auth.supervisor');

        if (!$query) {
            $result = $this->model->with('branch')
                ->whereNotIn('id', $supervisor)
                ->orderBy('id', 'asc')
                ->get();
        } else {
            // 若有查询参数
            $result = $this->model->with('branch')
                ->where('name', 'like', "%$query%")
                ->get();
        }

        return $result;
    }
    

    public function show($id)
    {
        $staff = $this->find($id);        
        if (!$staff) 
            return responseFail(404);        
        return $staff;          
    }


    public function store($request)
    {
        $staff = $this->create([
            'username' => $request->username,
            'passwd' => \Hash::make(DEFAULT_PASSWORD),
            'name' => $request->name,
            'branch_id' => $request->branch,
            'status' => STATUS_NORMAL
        ]);
        
        if ($result = !!$staff) {
            $staff->assignRole($request->roles);
        }
        if( $result )
            return responseSuccess('账号添加成功', $staff);

        return responseFail(500,'账号添加失败');
    }


    public function renew($request, $id)
    {
        \DB::beginTransaction();
        try {
            $result = $this->update([
                'username' => $request->username,
                'name' => $request->name,
                'branch_id' => $request->branch,
                'status' => STATUS_NORMAL
            ], $id);

            $this->find($id)->syncRoles($request->roles);
            
            \DB::commit();

            //\Event::fire(new UpdateStaffPermissionEvent($this->modle->find($id) ));

            event(new UpdateStaffPermissionEvent($this->find($id) ));
         
            return responseSuccess('账号更新成功', $result);       

        } catch (\Exception $e) {
            \DB::rollback();
            return responseFail(500,'账号更新失败');
        }
        
    }


    public function change($request, $id)
    {
        $row = $this->show($id);
        $status = $row->status;
        
        $result = $this->update([
                'status' => $status==1?0:1,
            ], $id);

        if(!!$result)
            return responseSuccess('账号状态更新成功', $row);
        
        return responseFail(500,'账号状态更新失败');        
    }
    

    public function chgpwd($request, $id)
    {
        $staff = Auth('admin')->user();

        if($staff->id != $id)
            return responseFail(500,'账号信息错误');

        if(!\Hash::check($request->oldpwd, $staff->password))
            return responseFail(500,'原密码不正确');

        if( strcmp($request->newpwd, $request->rnewpwd) !== 0)
            return responseFail(500,'两次输入的密码不一致');

        $result = $this->update([
            'password' => \Hash::make($request->newpwd),                
        ], $id);

        if(!!$result)
            return responseSuccess('密码更新成功', $this->find($id));
        
        return responseFail(500,'密码更新失败');         
        
    }


    public function charge($request)
    {
        $query = $request->term;
        
        if (preg_match('/^\d+$/i', $query)) {
            if (strlen($query) >= 4) {
                $result = $this->findWhere(array(['username', 'like', "%$query%"]));
            }
        }
        else {
            $result = $this->findWhere(array(['name', 'like', "%$query%"]));
        }
        
        return $result->toJson();
    }

    /**
     * 用户登录
     *
     * @param $request
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function login($request)
    {
        if ( !env('APP_DEBUG')) {
            if($request->captcha != \Session::get('captcha'))
                return responseFail(405,'验证码不正确');
        }
        

        // 判断用户使用什么字段登录
        $username = collect($request)->only(['username', 'mobile'])
            ->filter(function ($value, $key) {
                if ($value) {
                    $this->username = [$key => $value];
                }
                return !!$value;
            })->toArray();
            
        // 获取用户账号激活状态
        $active = $this->findByField($name = key($username), current($username));
        
        if( count($active) !== 1)
            return responseFail(401, '禁止登陆');
        
        if ( !$active->first()->status && $active->first()->name) {  // 若账号未激活
            return responseFail(401, '禁止登陆');
        }
        // 合并验证数据
        $data = array_merge($username, ['password'=>$request->password, 'status'=>STATUS_NORMAL ]);

        // 用户认证
        if (\Auth::guard($this->guard)->attempt($data)) {
            return responseSuccess('登录成功', $request, '/');
        }
        return responseFail(405, '用户名或密码错误');
    }

}